// server/middleware/browserCheck.js
import { defineEventHandler } from "h3";
import { getHeader } from "h3";
import userAgent from "user-agent";

export default defineEventHandler((event) => {
  const userAgentString = getHeader(event, "user-agent") || "";
  const acceptLanguage = getHeader(event, "accept-language") || "";
  const parsedUserAgent = userAgent.parse(userAgentString);

  // 定义需要提示的低版本浏览器
  const unsupportedBrowsers: any = {
    "Internet Explorer": { minVersion: 11 },
    "Microsoft Edge": { minVersion: 80 },
    Chrome: { minVersion: 50 },
    Firefox: { minVersion: 50 },
    Safari: { minVersion: 10 },
  };

  const browserName = parsedUserAgent.family;
  const browserVersion = parseInt(parsedUserAgent.major, 10);

  // 检查是否需要提示
  if (
    userAgentString.includes("Trident") ||
    (unsupportedBrowsers[browserName] &&
      browserVersion < unsupportedBrowsers[browserName].minVersion)
  ) {
    // 判断浏览器语言
    const isChinese = acceptLanguage.includes("zh");

    // 根据语言重定向到不同的提示页面
    if (isChinese) {
      return sendRedirect(event, "/update/browser/cn.html");
    } else {
      return sendRedirect(event, "/update/browser/en.html");
    }
  }
});
